<script setup lang="ts">
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CustomNavBar from './components/CustomNavBar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import ScGuess from '@/components/ScGuess.vue'
import { useGuessList } from '@/composables'

// 骨架屏控制响应式变量
const isLoading = ref(false)

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerDate = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
  // console.log(res.result)
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取首页热门数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

//页面挂载完成
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerDate(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

// // 获取猜你喜欢的实例
// const guessRef = ref<InstanceType<typeof ScGuess>>()
// // 滚触底事件
// const onScrollToLower = () => {
//   guessRef.value?.getMore()
// }
const { guessRef, onScrollToLower } = useGuessList()

// 下拉刷新
const isTriggered = ref(false)
const onRefresherRefresh = async () => {
  isTriggered.value = true
  guessRef.value?.reset()
  await Promise.all([
    getHomeBannerDate(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  isTriggered.value = false
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavBar></CustomNavBar>
  <!-- 滚动容器 -->
  <scroll-view
    class="scroll-view"
    scroll-y
    @scrolltolower="onScrollToLower"
    :refresher-enabled="true"
    @refresherrefresh="onRefresherRefresh"
    :refresher-triggered="isTriggered"
  >
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!-- 自定义轮播图 -->
      <ScSwiper :list="bannerList"></ScSwiper>
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <!-- 热门推荐 -->
      <HotPanel :list="hotList"></HotPanel>
      <!-- 猜你喜欢 -->
      <ScGuess ref="guessRef"></ScGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
  .scroll-view {
    flex: 1;
  }
}
</style>
